<template>
  <div class="app-container">
    <div class="section-container">
      <div class="form-container">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :label-width="ruleForm.fenceType ? '100px' : '80px'"
          class="demo-ruleForm"
        >
          <el-form-item label="围栏名称" prop="fenceName" :rules="[{ required: true, message: '请输入围栏名称', trigger: 'blur' }]">
            <el-input v-model="ruleForm.fenceName" maxlength="20" show-word-limit />
          </el-form-item>
          <el-form-item label="围栏类型" prop="fenceType">
            <el-radio-group v-model="ruleForm.fenceType" @change="changeFenceType">
              <el-radio :label="0">行政区域</el-radio>
              <el-radio :label="1">圆形</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="!ruleForm.fenceType">
            <p class="title"><span>*</span>主围栏</p>
            <el-form-item
              key="vin1"
              label="选择围栏"
              prop="vin1"
              :rules=" [
                { required: true, message: '请选择围栏', trigger: 'change' },
                { type: 'array', message: '请选择围栏' }
              ]"
            >
              <el-cascader
                v-model="ruleForm.vin1"
                :append-to-body="false"
                style="width: 100%"
                placeholder="请选择主围栏"
                clearable
                :options="shenglist1"
                :props="optionProps"
                @change="handleChange"
              />
            </el-form-item>
            <el-form-item label="围栏描述">
              <el-input
                v-model="ruleForm.mainFenceRemark"
                maxlength="200"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 5 }"
                show-word-limit
              />
            </el-form-item>
            <div class="sprit-line" />
            <p class="title">副围栏</p>
            <el-form-item label="选择围栏">
              <el-cascader
                v-model="ruleForm.vin2"
                :append-to-body="false"
                style="width: 100%"
                placeholder="请选择副围栏"
                :options="shenglist2"
                collapse-tags
                clearable
                :props="optionProps1"
                @change="handleChange1"
              />
            </el-form-item>
            <el-form-item label="围栏描述">
              <el-input
                v-model="ruleForm.auxiliaryFenceRemark"
                maxlength="200"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 5 }"
                show-word-limit
              />
            </el-form-item>
          </div>
          <div v-if="ruleForm.fenceType">
            <el-form-item
              key="dealerCode"
              label="无出行中心店"
              prop="dealerCode"
              :rules="[
                { required: true, message: '请选择无出行中心店', trigger: 'blur' },
                { type: 'array'}
              ]"
            >
              <el-select
                v-model="ruleForm.dealerCode"
                style="width: 100%"
                placeholder="请选择无出行中心店"
                clearable
                :multiple="multiple"
                filterable
                @change="getCircularCenter"
              >
                <el-option v-if="dealerOptions.length" label="全部" value="all" />
                <el-option v-for="(item, index) in dealerOptions" :key="index + '_'+ item.dealerCode" :label="item.dealerName" :value="item.dealerCode" />
              </el-select>
            </el-form-item>
            <el-form-item
              key="radius"
              label="半径"
              prop="radius"
              :rules=" [
                { required: true, message: '请输入半径', trigger: 'change' },
                { type: 'number', message: '半径必须为数字值' }
              ]"
            >
              <el-input v-model.number="ruleForm.radius" style="width: 90%" @blur="drawCircular" /> 米
            </el-form-item>
            <el-form-item label="围栏描述">
              <el-input
                v-model="ruleForm.mainFenceRemark"
                maxlength="200"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 5 }"
                show-word-limit
              />
            </el-form-item>
          </div>
          <div class="actions-button">
            <el-button
              style="width: 100%"
              type="primary"
              :loading="submitLoading"
              @click="submitForm('ruleForm')"
            >确定</el-button>
          </div>
        </el-form>
      </div>
      <div id="mapContainer" class="map-container" />
    </div>
  </div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { queryDealerList, addFence, queryFenceExist, queryFenceDetail, editFence } from '@/api/crossRegionalMonitoring'
// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '9f30a706f05000d328ede74a646cc6ac'
}
export default {
  name: 'FenclActions',
  data() {
    return {
      ruleForm: {
        fenceType: 0,
        fenceName: '',
        dealerCode: [],
        vin1: [],
        radius: ''
      },
      district: null,
      district1: null,
      polygons: [],
      polygons1: [],
      opts: {
        subdistrict: 0,
        extensions: 'all',
        level: 'district'
      },
      shenglist1: [],
      shenglist2: [],
      tempshenlist: [],
      chinas: [],
      chinas1: [],
      optionProps: {
        value: 'adcode',
        label: 'name',
        children: 'districtList',
        multiple: false
      },
      optionProps1: {
        value: 'adcode',
        label: 'name',
        children: 'districtList',
        multiple: true
      },
      dealerOptions: [],
      circles: [],
      circleCenter: null,
      isEdit: false,
      submitLoading: false,
      multiple: true
    }
  },
  created() {
    this.queryDealerList()
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap()
    })
  },
  methods: {
    init() {
      this.initForm()
      this.district && this.map.remove(this.polygons)
      this.district1 && this.map.remove(this.polygons1)
      this.circles && this.map.remove(this.circles)
    },
    // 获取4s店列表
    async queryDealerList() {
      this.listLoading = true
      const { data } = await queryDealerList({ dealerType: 1 })
      const items = data.data
      this.dealerOptions = items
    },
    /**
     * 初始化地图
     */
    initMap() {
      AMapLoader.load({
        key: '727004e71115f77ea27bdb30fd1447c4',
        version: '2.0',
        plugins: ['AMap.Scale', 'AMap.DistrictSearch']
      })
        .then((AMap) => {
          // 初始化地图
          this.map = new AMap.Map('mapContainer', {
            viewMode: '2D',
            resizeEnable: true,
            center: [116.30946, 39.937629],
            zoom: 13
          })
          this.map.addControl(new AMap.Scale())
          this.city_fun()
          // this.drawBounds();
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 获取省份城市数据
    city_fun() {
      var _ = this
      var opts = {
        subdistrict: 2,
        extensions: 'all',
        level: 'country'
      }
      this.district = new AMap.DistrictSearch(opts)
      this.district.search('中国', function(status, result) {
        if (status === 'complete') {
          // 省
          result.districtList[0].districtList.map((x) => {
            if (x.name === '台湾省') {
              x.districtList = [
                {
                  adcode: x.adcode,
                  level: 'city',
                  name: '台湾省'
                }
              ]
            }
            x.disabled = false
            _.shenglist1.push(x)
            _.shenglist2.push(x)
            _.tempshenlist.push(x)
          })
          console.log(_.shenglist1, '城市list')
          // _.$emit('inited', JSON.stringify(_.shenglist1))
        }
      })
    },
    unique(arr) {
      return Array.from(new Set(arr))
    },
    copyJson(json) {
      return JSON.parse(JSON.stringify(json))
    },
    // 加载行政区划插件
    createDistrict() {
      if (!this.district1) {
        const opts = {
          subdistrict: 1,
          extensions: 'all',
          level: 'city'
        }
        this.district1 = new AMap.DistrictSearch(opts)
      }
    },
    /**
     * 根据所选城市查找区域地图数据
     * target：所选城市
     * isMainFence 区分主围栏数据还是副围栏数据
    * */
    searchAreaData(target = [], isMainFence = true) {
      const _ = this
      if (isMainFence) {
        _.district1.search(
          target[target.length - 1],
          function(status, result) {
            if (status === 'complete') {
              const districtData = result.districtList[0]
              _.chinas.push(districtData)
              console.log(_.chinas)
              const bounds = districtData.boundaries
              bounds && _.drawBounds(bounds, isMainFence, '#0091ea', '#FF1493')
            }
          }
        )
      } else {
        target.map((x) => {
          this.district1.search(x, function(status, result) {
            if (status === 'complete') {
              const districtData = result.districtList[0]
              _.chinas1.push(districtData)
              // _.getData_map1(result.districtList[0])
              const bounds = districtData.boundaries
              bounds && _.drawBounds(bounds, isMainFence, '#0091ea', '#80d8ff')
            }
          })
        })
      }
    },
    /**
     * 根据主（副）围栏所选城市 禁用副（主）围栏城市数据中对应的城市
     * source：所选城市数据
     * target：目标城市数据
     */
    formartCityList(source, target) {
      target.map((x) => {
        if (x.districtList) {
          x.districtList.map((y) => {
            source.map((p) => {
              y.disabled = y.adcode === p
            })
          })
        }
      })
    },
    // 选择主围栏发生变化
    handleChange(val) {
      this.createDistrict()
      const mapciteylist = this.copyJson(this.ruleForm.vin1)
      this.map.remove(this.polygons)
      this.polygons = []
      this.chinas = []
      if (mapciteylist.length) {
        this.searchAreaData(mapciteylist, true)
        this.formartCityList(mapciteylist, this.shenglist2)
      } else {
        this.shenglist1 = this.copyJson(this.tempshenlist)
        this.shenglist2 = this.copyJson(this.tempshenlist)
      }
      this.map.remove(this.polygons1)
      this.$set(this.ruleForm, 'vin2', [])
    },
    // 选择副围栏发生变化
    handleChange1(val) {
      this.createDistrict()
      const mapciteylist = this.ruleForm.vin2
      this.map.remove(this.polygons1)
      this.polygons1 = []
      this.chinas1 = []
      if (mapciteylist.length) {
        let listlist = []
        mapciteylist.map((x, y) => {
          if (x.length === 2) {
            listlist.push(x[1])
          }
        })
        listlist = this.unique(listlist)
        this.searchAreaData(listlist, false)
        this.formartCityList(listlist, this.shenglist1)
      } else {
        this.map.remove(this.polygons1)
      }
      this.$forceUpdate()
    },
    /**
     * 绘制区域
     * bounds: 区域数据
     * isMainFence 区分主围栏还是次围栏
    */
    drawBounds(bounds, isMainFence = true, strokeColor, fillColor) {
      // console.log(isMainFence)
      const _ = this
      for (var i = 0, l = bounds.length; i < l; i++) {
        var polygon = new AMap.Polygon({
          map: _.map,
          strokeWeight: 1,
          strokeColor,
          fillColor,
          fillOpacity: 0.2,
          path: bounds[i]
        })
        isMainFence ? _.polygons.push(polygon) : _.polygons1.push(polygon)
      }
      if (isMainFence) {
        _.map.add(_.polygons)
        _.map.setFitView(_.polygons) // 视口自适应
      } else {
        _.map.add(_.polygons1)
        _.map.setFitView(_.polygons1)
      }
    },
    // 围栏类型发生改变
    changeFenceType(val) {
      if (val) {
        this.district && this.map.remove(this.polygons)
        this.district1 && this.map.remove(this.polygons1)
        this.ruleForm.vin1 = []
        this.ruleForm.vin2 = []
        this.shenglist1 = []
        this.shenglist2 = []
        this.city_fun()
      } else {
        if (this.circles) {
          console.log(this.circles)
          this.map.remove(this.circles)
          this.ruleForm.dealerCode = []
        }
      }
    },
    // 获取所选4s店的经纬度
    getCircularCenter(val) {
      // console.log(val)
      this.$forceUpdate()
      if (Array.isArray(val) && val.length) {
        const circles = []
        let selectedDealer = []
        if (val[val.length - 1] === 'all' || val.length === this.dealerOptions.length) {
          this.ruleForm.dealerCode = ['all']
          this.dealerOptions.map(item => {
            selectedDealer.push(item.dealerCode)
          })
        } else {
          const allIndex = val.findIndex(v => v === 'all')
          allIndex > -1 && val.splice(allIndex, 1)
          this.ruleForm.dealerCode = val
          selectedDealer = this.ruleForm.dealerCode
        }
        this.dealerOptions.forEach(item => {
          selectedDealer.forEach(childItem => {
            if (item.dealerCode === childItem) {
              const { latitude, longitude } = item
              circles.push({
                center: new AMap.LngLat(longitude, latitude)
              })
            }
          })
        })
        this.circles = circles
        this.drawCircular()
      }
    },
    // 绘制圆形区域
    drawCircular() {
      const { dealerCode, radius } = this.ruleForm
      const map = this.map
      map.clearMap()
      if (dealerCode.length && +radius) {
        this.circles && this.map.remove(this.circles)
        this.circles.forEach(circle => {
          const { center } = circle
          const circleOptions = {
            center,
            radius,
            map,
            strokeColor: '#0091ea', // 线颜色
            strokeWeight: 1, // 线宽
            fillColor: '#FF1493', // 填充颜色
            fillOpacity: 0.2
          }
          const circleObj = new AMap.Circle(circleOptions)
          this.circles.push(circleObj)
          this.map.add(circleObj)
          this.map.setFitView([circleObj])
          // circleObj.setMap(this.map)
        })
      } else {
        this.circles && this.map.remove(this.circles)
      }
    },
    searchFenceInfo() {
      const params = { id: this.fenceId }
      queryFenceDetail(params).then(res => {
        const { data } = res
        this.ruleForm = data.data
        const { fenceType, roundList } = this.ruleForm
        if (fenceType) {
          const dealerCode = roundList.map(item => (
            item.dealerCode
          ))
          this.ruleForm.dealerCode = dealerCode
          this.getCircularCenter(dealerCode)
          this.drawCircular()
        } else {
          const { auxiliaryFenceList, mainFenceList } = this.ruleForm
          if (mainFenceList) {
            const v1 = []
            mainFenceList.map((x) => { v1.push(x.provinceCode, x.cityCode) })
            this.$set(this.ruleForm, 'vin1', v1)
            this.handleChange()
          }
          if (auxiliaryFenceList) {
            const v2 = []
            auxiliaryFenceList.map((x) => {	v2.push([x.provinceCode, x.cityCode]) })
            this.$set(this.ruleForm, 'vin2', v2)
            this.handleChange1()
          }
          // console.log(this.ruleForm)
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          // 围栏类型为圆形
          if (this.ruleForm.fenceType) {
            const params = this.formartCirculParams()
            if (this.isEdit) {
              params['id'] = this.fenceId
              editFence(params).then(res => {
                this.resetForm('ruleForm')
              }).finally(() => {
                this.submitLoading = false
              })
            } else {
              addFence(params).then(res => {
                this.resetForm('ruleForm')
              }).finally(() => {
                this.submitLoading = false
              })
            }
          } else {
            this.judgeIsExit()
          }
        } else {
          return false
        }
      })
    },
    // 判断该区域是否已存在电子围栏
    judgeIsExit() {
      const { vin1, vin2 } = this.ruleForm
      vin1.length === 1 && vin1.push(vin1[0]) // 台湾省 只有一级行政区域 特殊处理
      const fenceList = [vin1, ...this.uniques([...vin2])]
      const params = []
      fenceList.map((x) => {
        params.push({
          provinceCode: x[0],
          cityCode: x[1]
        })
      })
      // 查询行政区围栏是否已存在
      queryFenceExist(params).then(res => {
        const { data } = res
        if (data.data) {
          const params = this.formatAreaParams(data.data)
          if (this.isEdit) {
            editFence(params).then(res => {
              this.resetForm('ruleForm')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            addFence(params).then(res => {
              this.resetForm('ruleForm')
            }).finally(() => {
              this.submitLoading = false
            })
          }
        }
      })
    },
    formatAreaParams(data) {
      // console.log(data)
      const list = {
        fenceType: 0,
        // createBy: getcookie('nickName'),
        fenceName: this.ruleForm.fenceName,
        auxiliaryFenceRemark: this.ruleForm.auxiliaryFenceRemark,
        mainFenceRemark: this.ruleForm.mainFenceRemark,
        position: []
      }
      const newList = []
      // console.log(data)
      // console.log(this.chinas)
      data.map(item => {
        // 主围栏
        this.chinas.map(p => {
          if (p.adcode === item.cityCode) {
            const yy = {
              cityCode: item.cityCode,
              provinceCode: item.provinceCode,
              mainFence: 1,
              // position: yui1.join('_'),
              cityName: this.sheng_fun(item.cityCode, 2),
              provinceName: this.sheng_fun(item.provinceCode, 1)
            }
            // 如果不存在
            if (!item.isHave) {
              var yui = []
              var yui1 = []
              p.boundaries.forEach(element => {
                yui = []
                element.forEach(pp => {
                  yui.push(pp.lng +	',' + pp.lat)
                })
                yui1.push(yui.join('|'))
              })
              yy['position'] = yui1.join('_')
              // var yy = {
              //   cityCode: item.cityCode,
              //   provinceCode: item.provinceCode,
              //   mainFence: 1,
              //   position: yui1.join('_'),
              //   cityName: this.sheng_fun(item.cityCode, 2),
              //   provinceName: this.sheng_fun(item.provinceCode, 1)
              // }
            } else {
              this.$delete(yy, 'position')
              // var yy = {
              //   cityCode: item.cityCode,
              //   provinceCode: item.provinceCode,
              //   mainFence: 1,
              //   cityName: this.sheng_fun(item.cityCode, 2),
              //   provinceName: this.sheng_fun(item.provinceCode, 1)
              // }
            }
            newList.push(yy)
          }
        })
        // 次围栏
        if (Array.isArray(this.ruleForm.vin2) && this.ruleForm.vin2.length) {
          // console.log(this.chinas1)
          this.chinas1.map((p) => {
            if (p.adcode === item.cityCode) {
              const yy = {
                cityCode: item.cityCode,
                provinceCode: item.provinceCode,
                mainFence: 0,
                // position: yui1.join('_'),
                cityName: this.sheng_fun(item.cityCode, 2),
                provinceName: this.sheng_fun(item.provinceCode, 1)
              }
              if (!item.isHave) {
                var yui = []
                var yui1 = []
                p.boundaries.forEach(op => {
                  op.forEach(pp => { yui.push(pp.lng + ',' + pp.lat) })
                  yui1.push(yui.join('|'))
                })
                yy['position'] = yui1.join('_')
                // var yy = {
                //   cityCode: item.cityCode,
                //   provinceCode: item.provinceCode,
                //   mainFence: 0,
                //   position: yui1.join('_'),
                //   cityName: this.sheng_fun(item.cityCode, 2),
                //   provinceName: this.sheng_fun(item.provinceCode, 1)
                // }
              } else {
                this.$delete(yy, 'position')
                // var yy = {
                //   cityCode: item.cityCode,
                //   provinceCode: item.provinceCode,
                //   mainFence: 0,
                //   cityName: this.sheng_fun(item.cityCode, 2),
                //   provinceName: this.sheng_fun(item.provinceCode, 1)
                // }
              }
              newList.push(yy)
            }
          })
        }
      })
      list.list = newList
      this.isEdit && (list['id'] = this.fenceId)
      return list
    },
    sheng_fun(val, lev) {
      var ss = ''
      if (lev === 1) {
        this.shenglist1.map((x) => {
          if (x.adcode === val) {
            ss = x.name
          }
        })
      } else {
        this.shenglist1.map((x) => {
          if (x.name !== '台湾省') {
            x.districtList.map((y) => {
              if (y.adcode === val) {
                ss = y.name
              }
            })
          }
        })
      }
      return ss
    },
    uniques(matrix) {
      const res = {}
      matrix.map((item) => {
        item.sort((a, b) => a - b)
        res[item] = item
      })
      return Object.values(res)
    },
    // 整理圆形参数
    formartCirculParams() {
      const { fenceName, fenceType, mainFenceRemark, radius, dealerCode } = this.ruleForm
      const selectedDealer = []
      if (dealerCode.some(item => item === 'all')) {
        this.dealerOptions.forEach(item => {
          selectedDealer.push(item)
        })
      } else {
        this.dealerOptions.forEach(item => {
          dealerCode.forEach(childItem => {
            if (item.dealerCode === childItem) {
              selectedDealer.push(item)
            }
          })
        })
      }
      return {
        fenceName,
        fenceType,
        mainFenceRemark,
        radius,
        roundList: selectedDealer
      }
    },
    initForm() {
      for (var key in this.ruleForm) {
        if (Array.isArray[this.ruleForm[key]]) {
          this.ruleForm[key] = []
        } else {
          this.ruleForm[key] = ''
        }
      }
      this.ruleForm.fenceType = 0
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$emit('cancel')
      // console.log(111)
    }
  }
}
</script>
<style scoped>
  ::v-deep .el-cascader-panel{
    height: 189px;
  }
</style>
<style lang="scss" scoped>
.section-container {
  width: 100%;
  display: flex;
  text-align: left;
  .form-container {
    width: 35%;
    box-sizing: border-box;
    padding-right: 20px;
    .title {
      font-family: "PingFangSC-Semibold", "PingFang SC Semibold", "PingFang SC",
        sans-serif;
      font-weight: 650;
      font-size: 14px;
      color: #1a1a1a;
      span {
        font-family: "PingFangSC-Regular", "PingFang SC", sans-serif;
        font-weight: 400;
        color: #ca1616;
      }
    }
    .sprit-line {
      border-top: 1px solid #dcdfe6; /* 设置顶部边框，可以调整宽度、样式和颜色 */
      height: 0; /* 高度设置为0，使其为水平线的一部分 */
    }
  }
  .map-container {
    width: 65%;
    box-sizing: border-box;
    padding: 0 15px;
    min-height: 700px;
  }
}
</style>
